<?php


namespace App\Admin\Controllers;

use App\Models\AdminApiMenusModel;
use App\Models\AdminMenusModel;
use App\Models\AdminRolesModel;
use Illuminate\Support\Facades\Validator;

class MenusController extends Controller
{
    /**
     * 获取用户菜单
     * @return bool
     */
    public function getMenu()
    {
        if ($this->admin_info['is_admin'] == YES) {
            $menus_arr = AdminMenusModel::query()->get()->toArray();
        } else {
            $admin_roles = AdminRolesModel::query()->where('id', $this->admin_info['role_id'])->first();
            $admin_role_menu = array_filter(explode(',', $admin_roles->menu_ids));

            $menus_arr = [];
            $menus = AdminMenusModel::getAdminMenus($admin_role_menu);

            if (!empty($menus)) {
                $menus_arr = $menus->toArray();
            }
        }

        $api_menus = AdminApiMenusModel::query()->get()->toArray();
        $api_menus = array_column($api_menus, null, 'id');

        foreach ($menus_arr as &$menu) {
            $menu['api_menus'] = [];
            $api_menu_ids = array_filter(explode(',', $menu['api_menu_ids']));
            foreach ($api_menu_ids as $api_menu_id) {
                $arr = [];
                $this->getHasMenus($api_menus, $api_menu_id, $arr);
                $menu['api_menus'][] = $arr;
            }
        }

        $menu_list = array_values(listToTree($menus_arr));

        return $this->success($menu_list);
    }

    protected function getHasMenus($admin_menus, $id, &$arr)
    {
        if ($admin_menus[$id]['pid'] === 0) {
            $arr[] = $id;
        } else {
            $this->getHasMenus($admin_menus, $admin_menus[$id]['pid'], $arr);
            $arr[] = $id;
        }
        return true;
    }

    /**
     * 编辑菜单
     * @return bool
     */
    public function addOrEditMenu()
    {
        $params = $this->request->all();
        $validator = Validator::make($params, [
            'path' => ['required', 'max:255'],
            'name' => ['required', 'max:255'],
            'title' => ['required', 'max:255'],
            'icon' => ['max:255'],
            'component' => ['max:255'],
            'pid' => ['integer']
        ]);
        if ($validator->fails()) {
            return $this->fail(CODE_ERR_SYSTEM, $validator->errors()->first());
        }

        $api_menus = $params['api_menus'] ?? [];
        $menu_ids = [];
        foreach ($api_menus as $menu) {
            $menu_ids = array_values(array_unique(array_merge($menu_ids, $menu)));
        }
        asort($menu_ids);

        $pid = $params['pid'] ?? 0;
        $data = [
            'path' => $params['path'] ?? '',
            'name' => $params['name'] ?? '',
            'title' => $params['title'] ?? '',
            'icon' => $params['icon'] ?? '',
            'component' => $params['component'] ?? '',
            'pid' => $pid,
            'api_menu_ids' => implode(',', $menu_ids)
        ];

        if (!empty($params['menu_id'])) {
            $admin_roles = AdminRolesModel::query()->where('id', $this->admin_info['role_id'])->first();
            $admin_role_menu = array_filter(explode(',', $admin_roles->menu_ids));

            if (!in_array($params['menu_id'], $admin_role_menu) && $this->admin_info['is_admin'] == NO) {
                return $this->fail(CODE_ERR_DENY, '没有权限编辑此菜单');
            }

            $re = AdminMenusModel::query()->where('id', $params['menu_id'])->update($data);
        } else {
            $re = AdminMenusModel::query()->insert($data);
        }

        if (!$re) {
            return $this->fail(CODE_ERR_SYSTEM, 'admin_menu更新失败');
        }

        return $this->success();
    }

    protected function getMenuIds($admin_menus, $id, &$arr)
    {
        if ($admin_menus[$id]['pid'] == 0) {
            $arr[] = $id;
        } else {
            $this->getMenuIds($admin_menus, $admin_menus[$id]['pid'], $arr);
            $arr[] = $id;
        }

        return true;
    }

    /**
     * 删除菜单
     * @return bool
     */
    public function delMenu()
    {
        $menu_id = $this->request->post('menu_id', 0);

        if ($menu_id == 0) {
            return $this->fail(CODE_ERR_PARAM,'菜单不存在');
        }

        $admin_roles = AdminRolesModel::query()->where('id', $this->admin_info['role_id'])->first();
        $admin_role_menu = array_filter(explode(',', $admin_roles->menu_ids));

        if (!in_array($menu_id, $admin_role_menu) && $this->admin_info['is_admin'] == NO) {
            return $this->fail(CODE_ERR_DENY, '没有权限编辑此菜单');
        }

        $re = AdminMenusModel::query()->where('id', $menu_id)->delete();

        if (!$re) {
            $this->fail(CODE_ERR_SYSTEM, '删除admin_menus失败');
        }

        return $this->success();
    }
}
